package com.songcha.library_common.ui.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator
import com.songcha.library_common.R
import com.songcha.library_common.ui.view.loading.WaveLoadingView
import com.songcha.library_common.util.dp2px

/*import com.songcha.library_common.util.BitmapUtil
import com.songcha.library_common.util.LogUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.library_common.util.dp2px
import com.songcha.library_common.util.sp2px*/

class MovableIndicatorView
@JvmOverloads
constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0,
    defRes: Int = 0
) : View(context,attrs,defStyle,defRes) {
    private var mValue = 0f
    private lateinit var mPaint: Paint
    private var mIndicatorWidth = 0f

    init {
        initView(context, attrs)
    }

    private fun initView(context: Context, attrs: AttributeSet?){

        val ta = context.obtainStyledAttributes(attrs, R.styleable.MovableIndicatorView)
        val bgColor = ta.getColor(R.styleable.MovableIndicatorView_miv_background_color,Color.BLUE)
        mIndicatorWidth = ta.getDimension(R.styleable.MovableIndicatorView_miv_indicator_width,0f)
        ta.recycle()

        mPaint = Paint()
        mPaint.color = bgColor
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
    }

    fun startMoveX(startX:Float,endX:Float,duration:Long){
        val anim = ValueAnimator.ofFloat(startX,endX)
        anim.apply {
            anim.duration = duration
            interpolator= LinearInterpolator()
            addUpdateListener {
                mValue = it.animatedValue as Float
                invalidate()
            }
            start()
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val rectF = RectF().apply {
            left = mValue
            top = 0f
            right = mValue + mIndicatorWidth
            bottom = height.toFloat()
        }

        canvas.drawRect(rectF,mPaint)
    }

}